"""
主题管理API路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from app.database import get_async_db
from app.schemas.theme import (
    ThemeCreate, ThemeUpdate, ThemeResponse, ThemeListResponse
)
from app.services.theme_service import theme_service
from app.utils.exceptions import ThemeNotFoundError, DatabaseError, ValidationError
from app.utils.logger import logger

router = APIRouter(prefix="/themes", tags=["主题管理"])


@router.post("/", response_model=ThemeResponse, summary="创建主题")
async def create_theme(
    theme_data: ThemeCreate,
    db: AsyncSession = Depends(get_async_db)
):
    """
    创建新主题
    
    - **name**: 主题名称（必填）
    - **description**: 主题描述
    - **keywords**: 关键词列表
    - **style**: 写作风格
    - **target_audience**: 目标受众
    - **content_length**: 内容长度要求（默认1500字）
    - **is_active**: 是否启用（默认true）
    """
    try:
        theme = await theme_service.create_theme(db, theme_data)
        return ThemeResponse.from_orm(theme)
    
    except ValidationError as e:
        logger.warning(f"创建主题验证失败: {str(e)}")
        raise HTTPException(status_code=422, detail=str(e))
    
    except DatabaseError as e:
        logger.error(f"创建主题数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="创建主题失败")
    
    except Exception as e:
        logger.error(f"创建主题未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/", response_model=ThemeListResponse, summary="获取主题列表")
async def get_themes(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    active_only: bool = Query(False, description="只返回启用的主题"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取主题列表，支持分页
    
    - **skip**: 跳过的记录数（用于分页）
    - **limit**: 返回的记录数（最大100）
    - **active_only**: 是否只返回启用的主题
    """
    try:
        return await theme_service.get_themes(db, skip, limit, active_only)
    
    except DatabaseError as e:
        logger.error(f"获取主题列表数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取主题列表失败")
    
    except Exception as e:
        logger.error(f"获取主题列表未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/search", response_model=ThemeListResponse, summary="搜索主题")
async def search_themes(
    keyword: str = Query(..., description="搜索关键词"),
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    根据关键词搜索主题
    
    - **keyword**: 搜索关键词（在主题名称中查找）
    - **skip**: 跳过的记录数
    - **limit**: 返回的记录数
    """
    try:
        return await theme_service.search_themes(db, keyword, skip, limit)
    
    except DatabaseError as e:
        logger.error(f"搜索主题数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="搜索主题失败")
    
    except Exception as e:
        logger.error(f"搜索主题未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/active", response_model=List[ThemeResponse], summary="获取启用的主题")
async def get_active_themes(
    db: AsyncSession = Depends(get_async_db)
):
    """获取所有启用的主题"""
    try:
        themes = await theme_service.get_active_themes(db)
        return [ThemeResponse.from_orm(theme) for theme in themes]
    
    except DatabaseError as e:
        logger.error(f"获取启用主题数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取启用主题失败")
    
    except Exception as e:
        logger.error(f"获取启用主题未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/{theme_id}", response_model=ThemeResponse, summary="获取主题详情")
async def get_theme(
    theme_id: str,
    db: AsyncSession = Depends(get_async_db)
):
    """
    根据ID获取主题详情
    
    - **theme_id**: 主题ID
    """
    try:
        theme = await theme_service.get_theme_by_id(db, theme_id)
        return ThemeResponse.from_orm(theme)
    
    except ThemeNotFoundError:
        raise HTTPException(status_code=404, detail="主题不存在")
    
    except DatabaseError as e:
        logger.error(f"获取主题详情数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="获取主题详情失败")
    
    except Exception as e:
        logger.error(f"获取主题详情未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.put("/{theme_id}", response_model=ThemeResponse, summary="更新主题")
async def update_theme(
    theme_id: str,
    theme_data: ThemeUpdate,
    db: AsyncSession = Depends(get_async_db)
):
    """
    更新主题信息
    
    - **theme_id**: 主题ID
    - 其他字段为可选更新字段
    """
    try:
        theme = await theme_service.update_theme(db, theme_id, theme_data)
        return ThemeResponse.from_orm(theme)
    
    except ThemeNotFoundError:
        raise HTTPException(status_code=404, detail="主题不存在")
    
    except ValidationError as e:
        logger.warning(f"更新主题验证失败: {str(e)}")
        raise HTTPException(status_code=422, detail=str(e))
    
    except DatabaseError as e:
        logger.error(f"更新主题数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="更新主题失败")
    
    except Exception as e:
        logger.error(f"更新主题未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.delete("/{theme_id}", summary="删除主题")
async def delete_theme(
    theme_id: str,
    db: AsyncSession = Depends(get_async_db)
):
    """
    删除主题
    
    - **theme_id**: 主题ID
    
    注意：删除主题会同时删除相关的文章
    """
    try:
        success = await theme_service.delete_theme(db, theme_id)
        return {"success": success, "message": "主题删除成功"}
    
    except ThemeNotFoundError:
        raise HTTPException(status_code=404, detail="主题不存在")
    
    except DatabaseError as e:
        logger.error(f"删除主题数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="删除主题失败")
    
    except Exception as e:
        logger.error(f"删除主题未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.post("/{theme_id}/toggle", response_model=ThemeResponse, summary="切换主题状态")
async def toggle_theme_status(
    theme_id: str,
    db: AsyncSession = Depends(get_async_db)
):
    """
    切换主题的启用/禁用状态
    
    - **theme_id**: 主题ID
    """
    try:
        theme = await theme_service.toggle_theme_status(db, theme_id)
        return ThemeResponse.from_orm(theme)
    
    except ThemeNotFoundError:
        raise HTTPException(status_code=404, detail="主题不存在")
    
    except DatabaseError as e:
        logger.error(f"切换主题状态数据库错误: {str(e)}")
        raise HTTPException(status_code=500, detail="切换主题状态失败")
    
    except Exception as e:
        logger.error(f"切换主题状态未知错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")